package com.example.test.controller;

import com.example.test.model.Order;
import com.example.test.model.User;
import com.example.test.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

// http://localhost:8080/swagger-ui/index.html
// http://localhost:8080/v3/api-docs

@RestController
@RequestMapping("/api")
@Tag(name = "用户管理", description = "提供用户的创建、查询、更新、删除功能")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @PostMapping("/users")
    @Operation(summary = "创建新用户", description = "根据用户信息创建一个新用户")
    @ApiResponses(value = {
            @ApiResponse(
                    responseCode = "201", description = "用户创建成功",
                    content = @Content(mediaType = "application/json", schema = @Schema(implementation = User.class))),
            @ApiResponse(
                    responseCode = "500", description = "服务器内部错误",
                    content = @Content(mediaType = "application/json", schema = @Schema(type = "object")))
    })
    public ResponseEntity<User> createUser(
            @Parameter(description = "要创建的用户对象", required = true)
            @RequestBody User user) {
        try {
            userService.createUser(user);
            logger.info("用户创建成功 {}", user);
            return new ResponseEntity<>(user, HttpStatus.CREATED);
        } catch (Exception e) {
            logger.error("用户创建失败", e);
            return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/users/{id}")
    @Operation(summary = "根据用户ID获取用户信息", description = "根据用户ID获取指定用户的详细信息")
    @ApiResponses({
            @ApiResponse(
                    responseCode = "200", description = "成功获取用户信息",
                    content = @Content(mediaType = "application/json", schema = @Schema(implementation = User.class))),
            @ApiResponse(
                    responseCode = "404", description = "未找到指定用户",
                    content = @Content(mediaType = "application/json", schema = @Schema(type = "object"))),
            @ApiResponse(
                    responseCode = "500", description = "服务器内部错误",
                    content = @Content(mediaType = "application/json", schema = @Schema(type = "object")))
    })
    public ResponseEntity<User> getUser(
            @PathVariable
            @Parameter(description = "用户的唯一ID", required = true, example = "1")
            long id) {
        try {
            User user = userService.getUserById(id);

            if (user == null)
                return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);
            return new ResponseEntity<>(user, HttpStatus.OK);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/users")
    @Operation(summary = "获取所有用户（分页查询）", description = "根据分页参数获取用户列表")
    @ApiResponses({
            @ApiResponse(
                    responseCode = "200", description = "成功获取用户列表",
                    content = @Content(mediaType = "application/json", schema = @Schema(implementation = User.class))),
            @ApiResponse(
                    responseCode = "500", description = "服务器内部错误",
                    content = @Content(mediaType = "application/json", schema = @Schema(type = "object")))
    })
    public ResponseEntity<List<User>> getUsers(
            @RequestParam(defaultValue = "0")
            @Parameter(description = "分页查询的起始位置", example = "0")
            int offset,
            @RequestParam(defaultValue = "10")
            @Parameter(description = "每页返回的用户数量", example = "10")
            int limit) {
        try {
            return new ResponseEntity<>(userService.getUsers(offset, limit), HttpStatus.OK);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @GetMapping("/users/{id}/recentOrders")
    @Operation(summary = "获取用户最近的十笔订单", description = "根据用户ID获取用户的详细信息和最近的10笔订单")
    @ApiResponses({
            @ApiResponse(
                    responseCode = "200", description = "成功返回用户信息和最近的订单列表",
                    content = @Content(mediaType = "application/json", schema = @Schema(implementation = User.class))),
            @ApiResponse(
                    responseCode = "404", description = "未找到指定用户",
                    content = @Content(mediaType = "application/json", schema = @Schema(type = "object"))),
            @ApiResponse(
                    responseCode = "500", description = "服务器内部错误",
                    content = @Content(mediaType = "application/json", schema = @Schema(type = "object")))
    })
    public ResponseEntity<User> getUserWithRecentOrders(
            @Parameter(description = "用户的唯一ID", example = "1")
            @PathVariable long id) {
        try {
            User user = userService.getUserById(id);

            if (user == null)
                return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);

            List<Order> recentOrders = userService.getRecentOrdersByUserId(id);
            user.setRecentOrders(recentOrders);
            return new ResponseEntity<>(user, HttpStatus.OK);
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @PutMapping("/users/{id}")
    @Operation(summary = "更新用户信息", description = "根据用户ID更新用户的详细信息")
    @ApiResponses({
            @ApiResponse(
                    responseCode = "200", description = "用户更新成功",
                    content = @Content(mediaType = "application/json", schema = @Schema(implementation = User.class))),
            @ApiResponse(
                    responseCode = "404", description = "用户未找到",
                    content = @Content(mediaType = "application/json", schema = @Schema(type = "object"))),
            @ApiResponse(
                    responseCode = "500", description = "服务器内部错误",
                    content = @Content(mediaType = "application/json", schema = @Schema(type = "object")))
    })
    public ResponseEntity<User> updateUser(
            @PathVariable
            @Parameter(description = "要更新的用户的唯一ID", required = true, example = "1")
            long id,
            @RequestBody
            @Parameter(description = "更新后的用户信息", required = true)
            User user) {
        try {
            if (userService.getUserById(id) == null)
                return new ResponseEntity<>(HttpStatus.NOT_FOUND);

            user.setId(id);
            userService.updateUser(user);
            logger.info("用户更新成功 {}", user);
            return new ResponseEntity<>(user, HttpStatus.OK);
        } catch (Exception e) {
            logger.error("用户更新失败", e);
            return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

    @DeleteMapping("/users/{id}")
    @Operation(summary = "删除用户", description = "根据用户ID删除用户")
    @ApiResponses({
            @ApiResponse(
                    responseCode = "200", description = "用户删除成功",
                    content = @Content(mediaType = "application/json", schema = @Schema(implementation = User.class))),
            @ApiResponse(
                    responseCode = "404", description = "用户未找到",
                    content = @Content(mediaType = "application/json", schema = @Schema(type = "object"))),
            @ApiResponse(
                    responseCode = "500", description = "服务器内部错误",
                    content = @Content(mediaType = "application/json", schema = @Schema(type = "object")))
    })
    public ResponseEntity<String> deleteUser(
            @PathVariable
            @Parameter(description = "要删除的用户的唯一ID", required = true, example = "1")
            long id) {
        try {
            User user = userService.getUserById(id);

            if (user == null)
                return new ResponseEntity<>(null, HttpStatus.NOT_FOUND);

            userService.deleteUserById(id);
            logger.info("用户删除成功 {}", user);
            return new ResponseEntity<>("删除用户成功", HttpStatus.OK);
        } catch (Exception e) {
            logger.error("用户删除失败", e);
            return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }
}
